﻿package com.projects.xenia.global_modules;

import java.io.File;
import java.lang.reflect.Array;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.xml.datatype.Duration;

import com.projects.xenia.Documents_Location;
import com.projects.xenia.R;
import com.projects.xenia.ref_classes.GoodsRefItem;

import android.content.ContentValues;
import android.content.Context;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.widget.ListView;
import android.widget.Toast;


public class MainGlobalModule {
	
	static public Object DocumentClass;	
	static public Documents_Location Documents_Location;
	
	static public Context Cntx;
	static public SQLiteDatabase DBE;	
	static public HashMap<String, String> SettingsCollection;
	static public HashMap<String, String> ConstantsCollection;
	
	static public String SelectedId;
	
	static public SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");	
	static public SimpleDateFormat fdf = new SimpleDateFormat("dd-MM-yy");
	
	static public Date NullDate = new Date(0, 0, 1);
	
	static public String StoragePath;
	static public String PhotoReportsImagesPath;
	static public String GoodsImagesPath;
	static public String GoodsImagesThumbsPath;
	static public String UpdatePath; 
	static public String TemporaryPath;
	
	static public ArrayList<GoodsRefItem> GoodsRef = new ArrayList<GoodsRefItem> ();
	static public ArrayList<GoodsRefItem> GoodsTreeRef = new ArrayList<GoodsRefItem> ();
	
	public static void Vibrate () {
		
		Vibrator vb = (Vibrator) Cntx.getSystemService(Context.VIBRATOR_SERVICE);
		vb.vibrate(30);
		
	}
	
	
	public static void setBackGround (ListView LV) {
		
		LV.setScrollingCacheEnabled(true);
    	LV.setCacheColorHint(Color.TRANSPARENT);
    	
		File ImgPath = new File (String.format("%s/%s.jpg", MainGlobalModule.StoragePath,"mesh"));        
	    if (ImgPath.exists()==true) {	    		    	
	    	Drawable Img = Drawable.createFromPath(ImgPath.getAbsolutePath());
	        LV.setBackgroundDrawable(Img);
	    }
	    else
	    {
	    	LV.setBackgroundResource(R.drawable.mesh);
	    }
	    	
	}
	
	public static double GetOffersConditionsGoodsCount (String DocId , String offers_condition_id , String GoodsId ) {
		
		double _result = 0; 
		
		Cursor _cursor = DBE.rawQuery("select offervalue from xdoc_Orders_O o where o.hdoc_id = ? and o.offers_conditions_id = ? and o.goods_id = ?", new String [] {DocId,offers_condition_id,GoodsId});
		if (_cursor.getCount()>0) {
			_cursor.moveToFirst();
			_result = _cursor.getDouble(0); 
		}
		
		return (_result);
		
	}
	
	public static boolean ExistsOffersByGoodsId (String DocId , String GoodsId ) {
		
		Cursor _cursor = DBE.rawQuery("select hdoc_id from xdoc_Orders_O o where o.hdoc_id = ? and o.goods_id = ?", new String [] {DocId,GoodsId});
		
		return (_cursor.getCount()>0);
		
	}
	

	public static boolean ExistsBonusByOffers (String DocId , String OffersId) {
		
		Cursor _cursor = DBE.rawQuery("select hdoc_id from xdoc_Orders_B b where b.hdoc_id = ? and b.offers_id = ?", new String [] {DocId,OffersId});
		return (_cursor.getCount()>0);
		
	}

	
	private static void GetOffersAssortmentsListNext (ArrayList<String> offerassortmentslist, String GoodsParentId) {
		
		Cursor offerassortmentslist_cursor = DBE.rawQuery("select distinct g.id, g.isfolder from xref_goods g where g.parentid = ?", new String [] {GoodsParentId});
		if (offerassortmentslist_cursor.getCount()>0){
			offerassortmentslist_cursor.moveToFirst();
			while (!offerassortmentslist_cursor.isAfterLast()){
				offerassortmentslist.add(offerassortmentslist_cursor.getString(0));
				if (offerassortmentslist_cursor.getInt(1)==1) {
					 GetOffersAssortmentsListNext (offerassortmentslist, offerassortmentslist_cursor.getString(0));	
				}			
				offerassortmentslist_cursor.moveToNext();
			}
			offerassortmentslist_cursor.close();
		}
		
	}
	
	public static ArrayList<String>  GetOffersAssortmentsList () {
		
		return GetOffersAssortmentsList (null);
		
	}
	
	public static ArrayList<String>  GetOffersAssortmentsList (String OffersId) {
		
		ArrayList<String> offerassortmentslist = new ArrayList<String>();
		
		Cursor offerassortmentslist_cursor;
		
		if (OffersId==null) {
			offerassortmentslist_cursor  = DBE.rawQuery("select distinct g.id, g.isfolder from xref_Offers_Conditions_Assortments o inner join xref_goods g on o.goods_id = g.id", null);
		}
		else
		{
			offerassortmentslist_cursor  = DBE.rawQuery("select distinct g.id, g.isfolder from xref_Offers_Conditions_Assortments o inner join xref_Offers_Conditions c on o.offers_condition_id = c.id  inner join xref_goods g on o.goods_id = g.id where c.offers_id = ?", new String []{OffersId});
		}
		
		if (offerassortmentslist_cursor.getCount()>0){
			offerassortmentslist_cursor.moveToFirst();
			while (!offerassortmentslist_cursor.isAfterLast()){
				offerassortmentslist.add(offerassortmentslist_cursor.getString(0));
				if (offerassortmentslist_cursor.getInt(1)==1) {
					GetOffersAssortmentsListNext (offerassortmentslist, offerassortmentslist_cursor.getString(0));
				}
				offerassortmentslist_cursor.moveToNext();
			}
			offerassortmentslist_cursor.close();
		}
		
		return (offerassortmentslist);
		
	}
	
	public static String GetCustomerPriceCategoy (String Customers_id) {
		
		String _PriceCatogory = MainGlobalModule.ConstantsCollection.get("DefPriceCategory");
		
		Cursor PriceCatogoryCursor = MainGlobalModule.DBE.rawQuery("select pricecategory_id from xref_CustomersDiscounts where customers_id = ? and is_default = 1", new String [] {Customers_id});			
		if (PriceCatogoryCursor.getCount()>0){
			PriceCatogoryCursor.moveToFirst();
			_PriceCatogory = PriceCatogoryCursor.getString(0);
		}
		
		return (_PriceCatogory);
		
	}
	
	
	public static boolean CheckExhacngeTime () {
		
		return (true);
		
	}
	
	public static boolean CheckLocationToday (boolean Silence) {
		
		boolean _result = true;		
		boolean LocationFirstOn = Boolean.parseBoolean(ConstantsCollection.get("LocationFirstOn"));
		
		if (LocationFirstOn) {			
			Cursor LocationData = MainGlobalModule.DBE.query("xdoc_gpslog", new String [] {"Accuracy"}, "date (date_create) = date ('now') and type_xdoc = 0", null, null, null, null);			
			_result = LocationData.getCount()>0;
			if (!Silence & !_result) {
				Toast.makeText(Cntx, "Необходимо снять первую координату !", Toast.LENGTH_SHORT).show();
			}
		}		
		
		return (_result);
		
	}
	
	public static boolean CheckMobileNetworkSettings () {
		
		ConnectivityManager ConnectivityManager = (ConnectivityManager) Cntx.getSystemService(Cntx.CONNECTIVITY_SERVICE);
		NetworkInfo infomobile = ConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		
		TelephonyManager telephonyManager = (TelephonyManager)Cntx.getSystemService(Cntx.TELEPHONY_SERVICE);
		GsmCellLocation cellLocation = (GsmCellLocation) telephonyManager.getCellLocation();
		
		if (cellLocation!=null && cellLocation.getCid()>0) {		
			try {		
				boolean isconnect = infomobile.isConnectedOrConnecting();
				if (isconnect == false) {
					Toast xtoast = Toast.makeText(Cntx, "Вкл. опцию мобильный интернет !!!", Toast.LENGTH_SHORT);
					xtoast.show();	
					return (true);
				}			
				} catch (Exception e) {
			
			}		
		}
		
		return (true);
	
	}
	
	public static boolean CheckGPSSettings (boolean silent) {
		
		try {
			
			LocationManager MyGPSLocation = (LocationManager)Cntx.getSystemService(Cntx.LOCATION_SERVICE);
			
			boolean LocationGPSMustOn = Boolean.parseBoolean(ConstantsCollection.get("LocationGPSMustOn"));
			boolean LocationNetMustOn = Boolean.parseBoolean(ConstantsCollection.get("LocationNetMustOn"));
			
			if (LocationGPSMustOn && !MyGPSLocation.isProviderEnabled(MyGPSLocation.GPS_PROVIDER)) {
				if (!silent) {
					Toast.makeText(Cntx, "Вкл. источник местоположения спутники GPS !!!", Toast.LENGTH_SHORT).show();	
				}				
				return (false);
			}
			
			if (LocationNetMustOn && !MyGPSLocation.isProviderEnabled(MyGPSLocation.NETWORK_PROVIDER)) {
				if (!silent) {
					Toast.makeText(Cntx, "Вкл. источник местоположения моб.сети и WiFi!!!", Toast.LENGTH_SHORT).show();
				}
				return (false);
			}			
			
		} catch (Exception e) {
			
			if (!silent) {
				Toast xtoast = Toast.makeText(Cntx, "ошибка определения GPS !!!", Toast.LENGTH_SHORT);
				xtoast.show();
			}

		}
		
		return (true);
	
	}

	
	public static Cursor GetAssortmentsGoodsRefCursorByCustomers (String CustomersId,String PriceCategory, String Firm, String AccType, String Department) {
		
		Cursor SimpleCursor = MainGlobalModule.DBE.rawQuery("select assortmentslist_id from xref_CustomersAssortments where customers_id = ?", new String [] {CustomersId});
		if (SimpleCursor.getCount()>0) {
			SimpleCursor.moveToFirst();
			String AssortmentListId = SimpleCursor.getString(0);
			return (GetAssortmentsGoodsRefCursorByAssortmentsListId (AssortmentListId,PriceCategory, Firm, AccType, Department));
		}
		return (null);
		
	}
	
	public static Cursor GetAssortmentsGoodsRefCursorByAssortmentsListId (String AssortmentListId,String PriceCategory, String Firm, String AccType, String Department) {
		
		Cursor GoodsCursor = MainGlobalModule.DBE.rawQuery("select distinct g.id,g.parentid,g.article,g.descr_long,g.isfolder,g.weight,g.volume,g.minimum_order,p.price,r.restvalue,g.measure_base,m.descr,gm.mul,x.factor, x.target FROM xref_goods g inner join xref_AssortmentsItems x on g.id = x.goods_id and x.assortmentslist_id = ? left outer join xref_goodsprices p  on g.id = p.goods_id and p.pricecategory_id = ? LEFT outer JOIN xref_goodsrests r ON g.id = r.goods_id AND r.firms_id = ? AND r.acctype = ? AND r.departments_id = ? left outer join xref_GoodsMeasures gm on g.measure_base = gm.id left outer join xref_Measures m on gm.measures_id = m.id ORDER BY g.isfolder desc,g.descr_long", new String [] {AssortmentListId,PriceCategory,Firm,AccType,Department});		
		return (GoodsCursor);
		
	}	

	
	public static GoodsRefItem GetGoodsRefItemByGoodsId (String GoodsId,String PriceCategory, String Firm, String AccType, String Department ) {
		
		Cursor GoodsCursor = MainGlobalModule.DBE.rawQuery("select distinct g.id,g.parentid,g.article,g.descr_long,g.isfolder,g.weight,g.volume,g.minimum_order,p.price,r.restvalue,g.measure_base,m.descr,gm.mul FROM xref_goods g left outer join xref_goodsprices p  on g.id = p.goods_id and p.pricecategory_id = ? LEFT outer JOIN xref_goodsrests r ON g.id = r.goods_id AND r.firms_id = ? AND r.acctype = ? AND r.departments_id = ? left outer join xref_GoodsMeasures gm on g.measure_base = gm.id left outer join xref_Measures m on gm.measures_id = m.id WHERE g.id = ? ORDER BY g.isfolder desc,g.descr_long", new String [] {PriceCategory,Firm,AccType,Department,GoodsId});
		if (GoodsCursor.getCount() > 0) {
			GoodsCursor.moveToFirst();
			
			GoodsRefItem gi = new GoodsRefItem();
			
			gi.article = GoodsCursor.getString(2);
			gi.descr = GoodsCursor.getString(3);
			gi.id = GoodsCursor.getString(0);
			gi.isfolder = GoodsCursor.getInt(4);
			gi.measure_base_descr = GoodsCursor.getString(11);
			gi.measure_base_factor = GoodsCursor.getDouble(0);
			gi.measure_base_id = GoodsCursor.getString(10);
			gi.minimum_order = GoodsCursor.getDouble(7);
			gi.parentid = GoodsCursor.getString(1);
			gi.position = 0;
			gi.price = GoodsCursor.getDouble(8);
			gi.rest = GoodsCursor.getDouble(9);
			gi.volume = GoodsCursor.getDouble(6);
			gi.weight = GoodsCursor.getDouble(5);
			gi.rule_factor = 0;
			gi.target = 0;
			GoodsCursor.close();
			
			return gi;
			
		}
		
		return null;
		
	}
	
	
	private static String GetSortingStr (int Sorting) {
		
		String SortingString="";
		
		switch (Sorting) {			
			case 0:
				SortingString = "g.descr_long";
				break;
			case 1:			
				SortingString = "g.descr_short";
				break;
			case 2:			
				SortingString = "p.price";
				break;
			case 3:			
				SortingString = "g.weight";
				break;
			case 4:			
				SortingString = "g.volume";
				break;
			case 5:			
				SortingString = "gm.mul";
				break;						
			default:
				break;
		}
		
		
		return (SortingString);
		
	}
	
	public static Cursor GetGoodsRefCursorByParentId (String GoodsId,String PriceCategory, String Firm, String AccType, String Department, int Sorting) {		
		 		
		Cursor GoodsCursor = MainGlobalModule.DBE.rawQuery("select distinct g.id,g.parentid,g.article,g.descr_long,g.isfolder,g.weight,g.volume,g.minimum_order,p.price,r.restvalue,g.measure_base,m.descr,gm.mul FROM xref_goods g left outer join xref_goodsprices p  on g.id = p.goods_id and p.pricecategory_id = ? LEFT outer JOIN xref_goodsrests r ON g.id = r.goods_id AND r.firms_id = ? AND r.acctype = ? AND r.departments_id = ? left outer join xref_GoodsMeasures gm on g.measure_base = gm.id left outer join xref_Measures m on gm.measures_id = m.id WHERE g.parentid = ? ORDER BY g.isfolder desc,"+GetSortingStr (Sorting), new String [] {PriceCategory,Firm,AccType,Department,GoodsId});		
		return (GoodsCursor);
		
	}
	
	public static Cursor GetGoodsRefCursorByAssortmentId (String AssortmentId,String PriceCategory, String Firm, String AccType, String Department, int Sorting) {		
 		
		Cursor GoodsCursor = MainGlobalModule.DBE.rawQuery("select distinct g.id,g.parentid,g.article,g.descr_long,g.isfolder,g.weight,g.volume,g.minimum_order,p.price,r.restvalue,g.measure_base,m.descr,gm.mul,s.factor, s.target FROM xref_goods g inner join xref_AssortmentsItems s on g.id = s.goods_id and s.assortmentslist_id = ? left outer join xref_goodsprices p  on g.id = p.goods_id and p.pricecategory_id = ? LEFT outer JOIN xref_goodsrests r ON g.id = r.goods_id AND r.firms_id = ? AND r.acctype = ? AND r.departments_id = ? left outer join xref_GoodsMeasures gm on g.measure_base = gm.id left outer join xref_Measures m on gm.measures_id = m.id ORDER BY g.isfolder desc,"+GetSortingStr (Sorting), new String [] {AssortmentId,PriceCategory,Firm,AccType,Department});		
		return (GoodsCursor);
		
	}

	

	public static Cursor GetGoodsRefCursorByName (String searchstring, String PriceCategory, String Firm, String AccType, String Department, int Sorting) {
		
		searchstring = searchstring.substring(0,1).toUpperCase()+searchstring.substring(1,searchstring.length()).toLowerCase();
		
		String Like1 = "%"+searchstring+"%";
		String Like2 = "%"+searchstring.toLowerCase()+"%";
		String Like3 = "%"+searchstring.toUpperCase()+"%";		
		
		
		Cursor GoodsCursor = MainGlobalModule.DBE.rawQuery("select distinct g.id,g.parentid,g.article,g.descr_long,g.isfolder,g.weight,g.volume,g.minimum_order,p.price,r.restvalue,g.measure_base,m.descr,gm.mul FROM xref_goods g left outer join xref_goodsprices p  on g.id = p.goods_id and p.pricecategory_id = ? LEFT outer JOIN xref_goodsrests r ON g.id = r.goods_id AND r.firms_id = ? AND r.acctype = ? AND r.departments_id = ? left outer join xref_GoodsMeasures gm on g.measure_base = gm.id left outer join xref_Measures m on gm.measures_id = m.id where g.isfolder = 0 and (g.article||g.descr_long) like ? or (g.article||g.descr_long) like ? or (g.article||g.descr_long) like ?  ORDER BY g.isfolder desc,"+GetSortingStr (Sorting), new String [] {PriceCategory,Firm,AccType,Department,Like1,Like2,Like3});		
		return (GoodsCursor);
		
	}

	
	public static Cursor GetGoodsRefCursorBySalesTOPN (String Customers_Id, int TopLimit, String PriceCategory, String Firm, String AccType, String Department, int Sorting) {		
 		
		String SubQuery = "select t.goods_id as goods_id,sum (t.ordervalue) as sumordervalue from xdoc_orders_h h inner join xdoc_orders_t t on h.id = t.hdoc_id where date (h.date_create) > date ('now','-30 day')";
		
		if (Customers_Id != null) {
			SubQuery =  SubQuery + String.format(" and h.customers_id = '%s'", Customers_Id);
		}
		
						
		
		SubQuery = SubQuery+" group by t.goods_id order by sumordervalue desc";
		
		if (TopLimit > 0) {
			SubQuery = SubQuery + String.format(" limit %d", TopLimit);
		}		

		
		Cursor GoodsCursor = MainGlobalModule.DBE.rawQuery("select distinct g.id,g.parentid,g.article,g.descr_long,g.isfolder,g.weight,g.volume,g.minimum_order,p.price,r.restvalue,g.measure_base,m.descr,gm.mul FROM xref_goods g inner join ("+SubQuery+") x on g.id = x.goods_id left outer join xref_goodsprices p  on g.id = p.goods_id and p.pricecategory_id = ? LEFT outer JOIN xref_goodsrests r ON g.id = r.goods_id AND r.firms_id = ? AND r.acctype = ? AND r.departments_id = ? left outer join xref_GoodsMeasures gm on g.measure_base = gm.id left outer join xref_Measures m on gm.measures_id = m.id ORDER BY g.isfolder desc,"+GetSortingStr (Sorting), new String [] {PriceCategory,Firm,AccType,Department});		
		return (GoodsCursor);
		
	}
	
	public static Cursor GetGoodsRefCursorByBarcode (String Barcode,String PriceCategory, String Firm, String AccType, String Department) {
		
		Cursor GoodsCursor = MainGlobalModule.DBE.rawQuery("select distinct g.id,g.parentid,g.article,g.descr_long,g.isfolder,g.weight,g.volume,g.minimum_order,p.price,r.restvalue,g.measure_base,m.descr,gm.mul FROM xref_goods g inner join xref_GoodsBarcodes br on g.id = br.goods_id and br.barcode = ? left outer join xref_goodsprices p  on g.id = p.goods_id and p.pricecategory_id = ? LEFT outer JOIN xref_goodsrests r ON g.id = r.goods_id AND r.firms_id = ? AND r.acctype = ? AND r.departments_id = ? left outer join xref_GoodsMeasures gm on g.measure_base = gm.id left outer join xref_Measures m on gm.measures_id = m.id ORDER BY g.isfolder desc,g.descr_long", new String [] {Barcode,PriceCategory,Firm,AccType,Department});
		return (GoodsCursor);
		
	}	
	

	public static void GetChildGoodsRefByGoodsId (String GoodsId, int level) {
				
		try {			 
			
			Cursor GoodsCursor = MainGlobalModule.DBE.rawQuery("select distinct g.id,g.parentid,g.article,g.descr_long FROM xref_goods g WHERE g.parentid = ? and isfolder = 1 ORDER BY g.descr_long", new String [] {GoodsId});
			
			if (GoodsCursor.getCount() > 0){	
				GoodsCursor.moveToFirst();				
				while (!GoodsCursor.isAfterLast()) {				
					GoodsRefItem gi = new GoodsRefItem ();
					gi.id = GoodsCursor.getString(0);
					gi.parentid = GoodsCursor.getString(1);
					gi.article = GoodsCursor.getString(2);
					gi.descr = GoodsCursor.getString(3);
					gi.isfolder = level;					
					
					GoodsTreeRef.add(gi);
					
					GetChildGoodsRefByGoodsId (gi.id,level+1);
					GoodsCursor.moveToNext();
				}
				GoodsCursor.close();
			}
			} catch (Exception e) {
				e.printStackTrace();				
		}		
		
	}	
	

	
	public static String FormatDate (Date DateValue) {
		
		if (DateValue!=null) {
			return fdf.format(DateValue);	
		}
		else
		{
			return fdf.format(NullDate); 
		}
		
	}	
	
	public static String DateToSqlString (Date DateValue) {
		
		if (DateValue!=null) {
			return sdf.format(DateValue);	
		}
		else
		{
			return sdf.format(NullDate); 
		}
		 
	}
	
	public static Date SqlStringToDate (String StringValue) {
		
		Date DateValue;
		
		try {
			DateValue = sdf.parse(StringValue);
		} catch (Exception e) {
			DateValue = NullDate;
		}
		
		return DateValue;
		
	}
	
	public static final class DocumentsType {
		
		public static final int First = 0;
		public static final int Order = 1;
		public static final int Payment = 2;
		public static final int Return = 3;
		public static final int PhotoReport = 4;
		public static final int Visit = 5;
		
	}
	
	public static void ConstantsCollection_Initialize () {
		
		ConstantsCollection = new HashMap<String, String>();
		Cursor Result = DBE.rawQuery("select name,value from xsys_mobileconstants",null);
		if (Result.getCount()>0 ==true){			
			while (Result.moveToNext()){
				ConstantsCollection.put(Result.getString(0), Result.getString(1));
			}			
		}		
		
		GetChildGoodsRefByGoodsId (ConstantsCollection.get("DefGoodsGroup"),0);
		
	}	
	
	public static void SettingsCollection_Initialize () {  
		
		SettingsCollection = new HashMap<String, String>(); 
		
		SettingsCollection.put("LocalWebServiceURL", "192.168.0.10");
		SettingsCollection.put("PrimaryWebServiceURL", "192.168.0.10");
		SettingsCollection.put("SecondaryWebServiceURL", "192.168.0.10");		
		SettingsCollection.put("ManagerId", "");
		SettingsCollection.put("DeviceId", "");
		SettingsCollection.put("RestOrderPref","1");
		SettingsCollection.put("Version","1.5");
		SettingsCollection.put("GoodsSorting","0");
		SettingsCollection.put("LastUpdate","0");
		
		Iterator<String> myVeryOwnIterator =  SettingsCollection.keySet().iterator();		
		while(myVeryOwnIterator.hasNext()) {			
	    	Object Key = myVeryOwnIterator.next();	    	
	    	String Field = (String) (Key);
	    	String Value = (String) SettingsCollection.get(Key);
	    	Cursor Result = DBE.rawQuery("select value from xsys_settings where id = ?",new String [] {Field});	    	
	    	if (Result.getCount()==0) {
	    		ContentValues MyContentValues = new ContentValues();
		    	MyContentValues.put("id", Field);
		    	MyContentValues.put("value", Value);		    	
	    		DBE.insertOrThrow("xsys_settings", null, MyContentValues);
	    	}
	    	else
	    	{
	    		Result.moveToFirst();
	    		SettingsCollection.put(Field, Result.getString(0));
	    	}
	    }
		
	}
	
	public static void SettingsCollection_Update (String Field, String Value) {
		
		SettingsCollection.put(Field, Value);
		ContentValues MyContentValues = new ContentValues();
    	MyContentValues.put("id", Field);
    	MyContentValues.put("value", Value);	
		DBE.update("xsys_settings", MyContentValues, "id=?",new String [] {Field});
		
	}
	
	public static void SettingsCollection_GetSettings () {
		
		Iterator<String> myVeryOwnIterator =  SettingsCollection.keySet().iterator();
		Editor SettingsEditor = PreferenceManager.getDefaultSharedPreferences(Cntx).edit();
		
		while(myVeryOwnIterator.hasNext()) {			
	    	Object Key = myVeryOwnIterator.next();	    	
	    	String Field = (String) (Key);
	    	String Value = (String) SettingsCollection.get(Key);    	
	    	SettingsEditor.putString(Field, Value);
	    }		
		
		SettingsEditor.commit();
		
	}
		
	public static final String md5(final String s) {
	    try {
	        // Create MD5 Hash
	        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
	        digest.update(s.getBytes());
	        byte messageDigest[] = digest.digest();
	 
	        // Create Hex String
	        StringBuffer hexString = new StringBuffer();
	        for (int i = 0; i < messageDigest.length; i++) {
	            String h = Integer.toHexString(0xFF & messageDigest[i]);
	            while (h.length() < 2)
	                h = "0" + h;
	            hexString.append(h);
	        }
	        return hexString.toString();
	 
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return "";
	}
	
	public static void SettingsCollection_SaveSettings () {
		
		SharedPreferences Settings = PreferenceManager.getDefaultSharedPreferences(Cntx);
		Map<String, ?> MyMap = Settings.getAll(); 
		Iterator<String> myVeryOwnIterator = MyMap.keySet().iterator();		
		while(myVeryOwnIterator.hasNext()) {			
	    	Object Key = myVeryOwnIterator.next();	    	
	    	String Field = (String) (Key);
	    	String Value = (String) MyMap.get(Key);    	
	    	SettingsCollection_Update (Field, Value);
	    }
		
	}
	
}
